package com.wenzhoujie.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ScrollView;

import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.huewu.pla.lib.MultiColumnListView;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.huewu.pla.lib.internal.PLA_AdapterView.OnItemClickListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.wenzhoujie.ShareDetailActivity;
import com.wenzhoujie.adapter.PhotosAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.customview.SDMultiColumnListView;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.ShareItemModel;
import com.wenzhoujie.model.SharelistActModel;
import com.wenzhoujie.model.SharelistItemModel;
import com.wenzhoujie.model.SharelistItemModelnew;
import com.wenzhoujie.model.act.ShareActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.ViewInject;

public class PhotosFragment extends BaseFragment
{

	//@ViewInject(id = R.id.frag_photos_smclv_images)
	//private SDMultiColumnListView mSmclvImages = null;
	@ViewInject(id = R.id.act_share_ptrlv_all)
	private PullToRefreshScrollView mPtrlvAll = null;
	
	@ViewInject(id = R.id.list)
	private ListView mSmclvImages = null;

	private List<SharelistItemModel> mListModel = new ArrayList<SharelistItemModel>();
	private List<ShareItemModel> mListModel2 = new ArrayList<ShareItemModel>();
	private List<ShareItemModel> mListModelCache = new ArrayList<ShareItemModel>();
	private List<SharelistItemModelnew> mListModelCachenew = new ArrayList<SharelistItemModelnew>();
	private List<SharelistItemModelnew> mListModelnew = new ArrayList<SharelistItemModelnew>();
	private int mListSign[] = new int[1024];

	private PhotosAdapter mAdapter = null;

	private PhotosFragmentListener mListener = null;

	private int pageTotal;

	// ================提交服务器参数
	private int page;
	private int is_hot;
	private int is_new;
	private String cid;
	private String tag;

	public PhotosFragmentListener getmListener()
	{
		return mListener;
	}

	public void setmListener(PhotosFragmentListener mListener)
	{
		this.mListener = mListener;
	}

	public int getIs_hot()
	{
		return is_hot;
	}

	public void setIs_hot(int is_hot)
	{
		this.is_hot = is_hot;
	}

	public int getIs_new()
	{
		return is_new;
	}

	public void setIs_new(int is_new)
	{
		this.is_new = is_new;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_photos, container, false);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init()
	{
		initPullToRefreshScrollView();
		bindDefaultData();
		//initSDMultiColumnListView();
		
	}

	private void bindDefaultData()
	{
		//mAdapter = new PhotosAdapter(mListModel2, getActivity());
		mAdapter = new PhotosAdapter(mListModelnew, getActivity());
		
		mSmclvImages.setAdapter(mAdapter);
		
		
		/*mSmclvImages.getRefreshableView().setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id)
			{
				SharelistItemModel model = mAdapter.getItem((int) id);
				if (model != null)
				{
					if (!AppHelper.isEmptyString(model.getShare_id()))
					{
						Intent intent = new Intent();
						intent.setClass(App.getApplication(), ShareDetailActivity.class);
						intent.putExtra(ShareDetailActivity.EXTRA_SHARE_ID, model.getShare_id());
						startActivity(intent);
					} else
					{
						SDToast.showToast("分享id为空");
					}
				}
			}
		});*/
	}

/*	private void initSDMultiColumnListView()
	{
		mSmclvImages.setMode(Mode.BOTH);
		mSmclvImages.setOnRefreshListener(new OnRefreshListener2<MultiColumnListView>()
		{

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<MultiColumnListView> refreshView)
			{
				refresh();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<MultiColumnListView> refreshView)
			{
				loadMore();
			}

		});
		mSmclvImages.setRefreshing();
	}
*/

	private void initPullToRefreshScrollView()
	{
		mPtrlvAll.setMode(Mode.BOTH);
		mPtrlvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView)
			{
				refresh();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView)
			{
				loadMore();
			}
		});
		mPtrlvAll.setRefreshing();
	}
	
	protected void refresh()
	{
		page = 1;
		requestData(false);

	}

	protected void loadMore()
	{
		page++;
		if (page > pageTotal && pageTotal > 0)
		{
			SDToast.showToast("没有更多数据了");
			mPtrlvAll.onRefreshComplete();
		} else
		{
			requestData(true);
		}
	}

	private void requestData(final boolean isLoadMore)
	{
		RequestModel model = new RequestModel();
		model.put("act", "sharelist");
		model.put("cid", cid);
		model.put("tag", tag);
		model.put("is_hot", is_hot);
		model.put("is_new", is_new);
		model.put("page", page);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{//System.out.println("SharelistActModel: "+responseInfo.result);
				SharelistActModel actModel = JsonUtil.json2Object(responseInfo.result, SharelistActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{

						if (actModel.getPage() != null)
						{
							page = actModel.getPage().getPage();
							pageTotal = actModel.getPage().getPage_total();
						}
						//SDViewUtil.updateAdapterByList(mListModel, actModel.getItem(), mAdapter, isLoadMore);
						
						//System.out.println("Update now: "+actModel.getItem().size());
						
						//mListModelCache.clear();
						//for (int i = 0; i < actModel.getItem().size(); i++)
						{
							//SharelistItemModelnew model = (SharelistItemModelnew) actModel.getItem();//.get(i);
							//requestShareDetail(model.getShare_id(), actModel.getItem().size(), isLoadMore);
							//System.out.println("i: "+i+" S: "+model.getShare_id());
							//mListModelCachenew.add((SharelistItemModelnew) actModel.getItem());
							SDViewUtil.updateAdapterByList(mListModelnew,  actModel.getItem(), mAdapter, isLoadMore);
							setListViewHeightBasedOnChildren(mSmclvImages);
							//mListModelCachenew.clear();
						}

						if (mListener != null)
						{
							mListener.onSuccess(actModel, isLoadMore);
						}
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				AppHelper.hideLoadingDialog();
				mPtrlvAll.onRefreshComplete();
			}
		};

		InterfaceServer.getInstance().requestInterface(model, handler);
	}
	
//	private void requestShareDetail(String share_id, final int t, final boolean isLoadMore)
//	{
//		if (share_id != null)
//		{
//			RequestModel model = new RequestModel();
//			model.put("act", "share");
//			if (AppHelper.isLogin())
//			{
//				model.put("email", AppHelper.getLocalUser().getUser_name());
//				model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
//			}
//			model.put("share_id", share_id);
//			RequestCallBack<String> handler = new RequestCallBack<String>()
//			{
//
//				@Override
//				public void onStart()
//				{
//					//AppHelper.showLoadingDialog("请稍候...");
//				}
//
//				@Override
//				public void onSuccess(ResponseInfo<String> responseInfo)
//				{
//					ShareActModel actModel = JsonUtil.json2Object(responseInfo.result, ShareActModel.class);
//					if (!SDInterfaceUtil.isActModelNull(actModel))
//					{
//						if (actModel.getResponse_code() == 1)
//						{
//							//setShareItemModel(actModel.getItem());
//							//addFragments(mShareItemModel);
//							//bindModel(v, actModel.getItem());
//							mListModelCache.add(actModel.getItem());
//							//System.out.println("Add Item! "+actModel.getItem().getShare_id());
//							//mAdapter.updateListViewData(mListModelCache);
//							
//							if (t <= mListModelCache.size()){
//								SDViewUtil.updateAdapterByList(mListModel2, mListModelCache, mAdapter, isLoadMore);
//								setListViewHeightBasedOnChildren(mSmclvImages);
//								System.out.println("Total: "+mListModel2.size());
//							}
//						}
//					}
//				}
//
//				@Override
//				public void onFailure(HttpException error, String msg)
//				{
//
//				}
//
//				@Override
//				public void onFinish()
//				{
//					//AppHelper.hideLoadingDialog();
//				}
//			};
//
//			InterfaceServer.getInstance().requestInterface(model, handler);
//		}
//
//	}
//	
	public void setListViewHeightBasedOnChildren(ListView listView) {   
        // 获取ListView对应的Adapter   
        int totalHeight = 0;   
        for (int i = 0, len = mAdapter.getCount(); i < len; i++) {   
            // listAdapter.getCount()返回数据项的数目   
            View listItem = mAdapter.getView(i, null, listView);   
            // 计算子项View 的宽高   
            listItem.measure(0, 0);    
            // 统计所有子项的总高度   
            totalHeight += listItem.getMeasuredHeight();    
        }   
   
        ViewGroup.LayoutParams params = listView.getLayoutParams();   
        params.height = totalHeight+ (listView.getDividerHeight() * (mAdapter.getCount() - 1)) + 300;   
        // listView.getDividerHeight()获取子项间分隔符占用的高度   
        // params.height最后得到整个ListView完整显示需要的高度   
        listView.setLayoutParams(params);   
    }   

	public interface PhotosFragmentListener
	{
		public void onSuccess(SharelistActModel model, boolean isLoadMore);
	}

}